package com.talent.study.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName：Main
 * @Author: hszhou
 * @Date: 2025/1/18 15:14
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
public class MQTTExample {

    private static final Logger logger = LoggerFactory.getLogger(MQTTExample.class);
    private  static String broker = "tcp://127.0.0.1:18883";
    public static void main(String[] args) {

        for (int j = 0; j < 100; j++) {

            int finalJ = j;
            new Thread(()->{
                for (int k = 0; k < 1000; k++) {
                    connect("clientId-"+ finalJ +"-"+k);
                }
            },"Thread-"+j).start();


        }
    }


    public static void connect(String clientId){

        try {

            MqttClient client = new MqttClient(broker, clientId);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            client.connect(connOpts);
          logger.info("线程【{}】创建的客户端【{}】连接服务器",Thread.currentThread().getName(),clientId);
            // 在这里可以订阅主题、发布消息等操作
            //    client.disconnect();
//            while (true){
//                Thread.sleep(5000);
//                MqttMessage mqttMessage =new MqttMessage();
//                mqttMessage.setPayload(("我是客户端"+clientId+"发送的消息").getBytes(StandardCharsets.UTF_8));
//                client.publish("testtopic/1",mqttMessage);
//            }
        } catch (MqttException e) {

            e.printStackTrace();
        }
    }
}
